package com.play.airfight;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;

import androidx.annotation.NonNull;

import java.util.ArrayList;

@Deprecated
public class PlaneView extends SurfaceView {

    private static final String TAG = "PlaneView";

    public static float currentX;  // 飞机当前坐标
    public static float currentY;  // 飞机当前坐标
    private static int screenWidth;  // 全屏画布的宽
    private static int screenHeight;  // 全屏画布的高
    private static int bulletSpeed = 20; // 子弹的飞行速度
    private static int enemyDropSpeed = 5; // 敌人下落的速度

    private final static int FLY_BULLET_ENEMY = 0;  // 事件标志: 子弹飞行 / 敌人下落
    private final static int ADD_BULLET = 1;  // 事件标志：射击（增加子弹）
    private final static int ADD_ENMEY = 2;  // 事件标志：增加敌人

    private final static int SHOOTING_SPEED_PER_SCEOND = 5;// 每秒发射子弹数量
    private final static int ENEMY_ADD_PER_SCEOND = 1;// 每秒增加敌人的数量

    private final static int MAX_BULLET_SIZE = 10; // 屏幕上最大的 子弹 数量
    private final static int MAX_ENEMY_SIZE = 10; // 屏幕上最大的 敌人 数量

    public int driveSpeed = 100;

    // 敌人域
    private static ArrayList<Enemy> enemyList = new ArrayList<Enemy>();

    // 生成随机敌人
    public static class Enemy {
        public float currentX;
        public float currentY;
        int width = 100;
        int height = 50;
        int speed = enemyDropSpeed;

        public Enemy(float currentX, float currentY) {
            this.currentX = currentX;
            this.currentY = currentY;
        }

        private void drop() {
            currentY += speed;
        }
    }


    // 子弹集合域
    private static ArrayList<Bullet> bulletList = new ArrayList<Bullet>();

    // 子弹
    public static class Bullet {
        public float currentX;
        public float currentY;
        int width = 10;
        int height = 30;
        int speed = bulletSpeed;


        public Bullet(float currentX, float currentY) {
            this.currentX = currentX;
            this.currentY = currentY;
        }

        private void fly() {
            currentY -= speed;
        }

    }


    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FLY_BULLET_ENEMY:
                    if (bulletList.size() != 0) {
                        for (Bullet bullet : bulletList) {
                            bullet.fly();
                        }
                    }

                    if (enemyList.size() != 0) {
                        for (Enemy enemy : enemyList) {
                            enemy.drop();
                        }
                    }
                    // 碰撞检测
                    CollsionDetection();
                    break;
                case ADD_BULLET:
                    if (bulletList.size() >= MAX_BULLET_SIZE) {
                        bulletList.remove(0);
                    }
                    bulletList.add(new Bullet(currentX, currentY - plane.getHeight() / 2 - 5));
                    break;
                case ADD_ENMEY:
                    if (enemyList.size() >= MAX_ENEMY_SIZE) {
                        enemyList.remove(0);
                    }
                    enemyList.add(new Enemy((float) (Math.random() * screenWidth), 0));
                    break;
            }
            planeView.postInvalidate();
        }
    };


    // 子弹移动
    public Thread threadFly = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                handler.sendEmptyMessage(FLY_BULLET_ENEMY);
                try {
                    Thread.sleep(16);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    // 增加子弹
    public Thread threadAddBullet = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                handler.sendEmptyMessage(ADD_BULLET);
                try {
                    Thread.sleep(1000 / SHOOTING_SPEED_PER_SCEOND);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    public Thread threadAddEnemy = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                handler.sendEmptyMessage(ADD_ENMEY);
                try {
                    Thread.sleep(1000 / ENEMY_ADD_PER_SCEOND);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });


    public void setWidthHeight(int screenWidth, int screenHeight) {
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
    }

    static Bitmap plane;


    private static PlaneView planeView;

    // 懒汉单例
    public static PlaneView getPlaneView(Context context) {
        if (planeView == null) {
            planeView = new PlaneView(context);
        }
        planeView.setFocusable(true);
        return planeView;
    }

    public PlaneView(Context context) {
        super(context);
        plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.plane);
        setFocusable(true);
//        this.setZOrderOnTop(true);
//        this.getHolder().setFormat(PixelFormat.TRANSLUCENT);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint p = new Paint();
        canvas.drawBitmap(plane, (float) (currentX - plane.getWidth() / 2), (float) (currentY - plane.getHeight() / 2), p);
        if (bulletList.size() != 0) {
            for (Bullet bullet : bulletList) {
                Paint bp = new Paint();
                Rect rect = new Rect(
                        (int) (bullet.currentX - bullet.width / 2),
                        (int) (bullet.currentY - bullet.height / 2),
                        (int) (bullet.currentX + bullet.width / 2),
                        (int) (bullet.currentY + bullet.height / 2));
                canvas.drawRect(rect, bp);
            }
        }

        if (enemyList.size() != 0) {
            for (Enemy enemy : enemyList) {
                Paint bp = new Paint();
                Rect rect = new Rect(
                        (int) (enemy.currentX - enemy.width / 2),
                        (int) (enemy.currentY - enemy.height / 2),
                        (int) (enemy.currentX + enemy.width / 2),
                        (int) (enemy.currentY + enemy.height / 2));
                canvas.drawRect(rect, bp);
            }
        }
    }

    public void limitXY() {
        if (currentX >= screenWidth) {
            currentX = 1;
        }
        if (currentX <= 0) {
            currentX = screenWidth;
        }
        if (currentY >= screenHeight) {
            currentY = 40;
        }
        if (currentY <= 1) {
            currentY = screenHeight;
        }

        this.postInvalidate();
    }

    private static void CollsionDetection() {
        for (int i = 0; i < bulletList.size(); i++) {
            for (int j = 0; j < enemyList.size(); j++) {
                try {
                    if (isCollsionWithRect(bulletList.get(i), enemyList.get(j))) {
                        bulletList.remove(i);
                        enemyList.remove(j);
                    }
                } catch (IndexOutOfBoundsException e) {
//                    planeView.threadFly.interrupt();
//                    planeView.threadAddBullet.interrupt();
//                    planeView.threadAddEnemy.interrupt();
                    Log.e(TAG, "bulletList.size = " + bulletList.size());
                    Log.e(TAG, "i = " + i);
                    Log.e(TAG, "enemyList.size = " + enemyList.size());
                    Log.e(TAG, "j = " + j);
                } finally {

                }
            }
        }
    }

    // 碰撞检测
    public static boolean isCollsionWithRect(Bullet bullet, Enemy enemy) {
        int x1 = (int) (bullet.currentX - bullet.width / 2);
        int y1 = (int) (bullet.currentY - bullet.height / 2);
        int w1 = bullet.width;
        int h1 = bullet.height;

        int x2 = (int) (enemy.currentX - enemy.width / 2);
        int y2 = (int) (enemy.currentY - enemy.height / 2);
        int w2 = enemy.width;
        int h2 = enemy.height;


        //当矩形1位于矩形2的左侧
        if (x1 >= x2 && x1 >= x2 + w2) {
            return false;
            //当矩形1位于矩形2的右侧
        } else if (x1 <= x2 && x1 + w1 <= x2) {
            return false;
            //当矩形1位于矩形2的上方
        } else if (y1 >= y2 && y1 >= y2 + h2) {
            return false;
        } else if (y1 <= y2 && y1 + h1 <= y2) {
            return false;
        }
        //所有不会发生碰撞都不满足时，肯定就是碰撞了
        return true;

    }

}
